<?php

namespace app\admin\controller\hit;

use app\admin\model\Scenic;
use ba\Exception;
use Throwable;
use app\common\controller\Backend;

/**
 * 热门景区
 */
class HitScenic extends Backend
{
    /**
     * Scenic模型对象
     * @var object
     * @phpstan-var \app\admin\model\hit\HitScenic
     */
    protected object $model;

    protected string|array $defaultSortField = 'weigh,desc';

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['scenic'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\hit\HitScenic();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
//        $res->visible(['scenic' => ['name','cover','tags','banner','address','openTime','city_name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $scenic_ids = $data['scenic_ids'] ?? [];
                if(!$scenic_ids) throw new Exception('请选择景点');
                $res = [];
                foreach ($scenic_ids as $val){
                    $res[] = [
                      'scenic_id' => $val
                    ];
                }
                $result = $this->model->saveAll($res);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function getScenic(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }
        //查询现在已经添加的景点
        $scenic_ids = $this->model->column('scenic_id');

        $params = $this->request->get();
        $map = [];
        if(isset($params['name']) && $params['name']){
            $map[] = ['name','like','%'.$params['name'].'%'];
        }

        if(isset($params['province_name']) && $params['province_name']){
            $map[] = ['province_name','like','%'.$params['province_name'].'%'];
        }

        if(isset($params['city_name']) && $params['city_name']){
            $map[] = ['city_name','like','%'.$params['city_name'].'%'];
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = (new Scenic())
            ->field($this->indexField)
            ->alias($alias)
            ->where($map)
            ->where(['status' => 1])
            ->whereNotIn('id',$scenic_ids)
            ->order('id desc')
            ->paginate($limit);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }



    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}